import CommonHook from "@/hook/commonHook";
import { tableColumnMap } from "../data";
import { Modal, message } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { computed, createVNode, h } from "vue";
import {
  waitOrderPageDataApi,
  insuranceShipmentOrderApi,
  insuranceShipmentOrderPageStatApi,
  importOrderApi,
  cancelOrderApi,
  getInsuranceOrderFileApi
} from "@/api/waybillManagement/insurance/placeOrder";
export default function OperationHook(state: Base.GeneraDataType) {
  const { searchForm, tableData, loading, activeKey, pageStat, dialogOpts, tableRef } = state;
  const selectRows = computed<Array<ClientWaybillManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { downloadFileByUrl } = CommonHook();
  const getData = async () => {
    const params = {
      ...getParams()
    };
    loading.value = true;
    let requestFn;
    if (activeKey.value === "0") {
      requestFn = waitOrderPageDataApi;
    } else requestFn = insuranceShipmentOrderApi;
    return requestFn(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const pageStateic = () => {
    const params = getParams();
    return insuranceShipmentOrderPageStatApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, data);
        // activeKey.value = String(getNoZeroKey(pageStat.value, ["0", "1", "2", "3"]));
      }
    });
  };
  const getParams = () => {
    const { waybillNumList, bizIdList, addressTypeList, customerIdList, orderNoList, insuranceTypeList, insuranceCompanyIdList, pageNum, pageSize, total } = searchForm;
    const params: Parameters<typeof waitOrderPageDataApi>[0] = {
      waybillNumList: [],
      bizIdList,
      addressTypeList,
      customerIdList,
      orderNoList: [],
      insuranceTypeList,
      insuranceCompanyIdList,
      pageNum,
      pageSize,
      total,
      statusList: activeKey.value === "3" ? [3, 4] : [Number(activeKey.value)]
    };
    if (waybillNumList) {
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    }

    if (orderNoList) {
      params.orderNoList = orderNoList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    }

    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    getData();
  };
  //保险下单
  const addPlaceOrderHandle = (row: PlaceOrder.ListRows) => {
    dialogOpts.title = `保险下单`;
    dialogOpts.width = "700px";
    dialogOpts.type = 1;
    dialogOpts.component = "AddPlaceOrder";
    dialogOpts.passData = row;
    dialogOpts.visible = true;
  };

  //备注保险
  const modifyRemarkHandle = (row: PlaceOrder.ListRows) => {
    dialogOpts.title = `备注保险`;
    dialogOpts.width = "500px";
    dialogOpts.component = "ModifyRemark";
    dialogOpts.passData = row;
    dialogOpts.visible = true;
  };

  //修改保险
  const changePlaceOrderHandle = (row: PlaceOrder.ListRows) => {
    dialogOpts.title = `保险下单`;
    dialogOpts.width = "700px";
    dialogOpts.type = 2;
    dialogOpts.component = "AddPlaceOrder";
    dialogOpts.passData = row;
    dialogOpts.visible = true;
  };

  //导入下单
  const upDownHandle = () => {
    dialogOpts.title = `导入下单`;
    dialogOpts.width = "500px";
    dialogOpts.component = "UploadfileAndDownLoadTemplate";
    dialogOpts.visible = true;
  };

  const tableColumn = computed<Array<SuperTable.TableCoulmnItem | SuperTable.NestTableColumnItem>>(() => {
    return tableColumnMap[activeKey.value];
  });

  const importOrderHandle = (from: any) => {
    return importOrderApi(from);
  };
  //取消保险
  const cancelPlaceOrderHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选数据");
    Modal.confirm({
      title: "是否取消保险？",
      icon: createVNode(ExclamationCircleOutlined),
      content: "",
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        cancelOrderApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            getData();
          }
        });
      }
    });
  };

  //取消保险 单条
  const cancelPlaceOrderOneHandle = (row: PlaceOrder.ListRows) => {
    Modal.confirm({
      title: `是否取消保险？`,
      icon: createVNode(ExclamationCircleOutlined),
      content: h("div", { style: "font-size:16px;margin-top:20px" }, [h("p", `保险公司：${row.insuranceCompanyName}`), h("p", `投保金额：${row.insuranceAmount}`)]),
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        cancelOrderApi([row.id]).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            getData();
          }
        });
      }
    });
  };

  // 下载模板
  const downloadTemplateHandle = (row: PlaceOrder.ListRows) => {
    return getInsuranceOrderFileApi(row.id).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        downloadFileByUrl(data, `保险订单.docx`);
      }
    });
  };

  return {
    searchHandle,
    getData,
    addPlaceOrderHandle,
    changeTabHandle,
    pageStateic,
    tableColumn,
    upDownHandle,
    importOrderHandle,
    cancelPlaceOrderHandle,
    changePlaceOrderHandle,
    modifyRemarkHandle,
    downloadTemplateHandle,
    cancelPlaceOrderOneHandle
  };
}
